﻿
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;

namespace WebAPI.Util;

public class BasePageOutput<T>
    where T : new()
{
    public int Page { get; set; }

    public int PageSize { get; set; }

    public int Total { get; set; }

    public int TotalPages { get; set; }

    public List<T>? Items { get; set; }

    public bool HasPrevPage { get; set; }

    public bool HasNextPage { get; set; }
}

public static class BasePageOutputExtensions
{
    /// <summary>
    /// 分页拓展
    /// </summary>
    /// <param name="entity"></param>
    /// <param name="pageIndex"></param>
    /// <param name="pageSize"></param>
    /// <returns></returns>
    public static BasePageOutput<T> ToPagedList<T>(List<T> entity, int pageIndex, int pageSize)
        where T : new()
    {
        int total = entity?.Count() ?? 0;
        var totalPages = (int)Math.Ceiling(total / (double)pageSize);
        var items = entity?.Skip(pageIndex * pageSize)
                ?.Take(pageSize)?.ToList() ?? null;
        return new BasePageOutput<T>
        {
            Page = pageIndex,
            PageSize = pageSize,
            Items = items,
            Total = total,
            TotalPages = totalPages,
            HasNextPage = pageIndex < totalPages,
            HasPrevPage = pageIndex - 1 > 0
        };
    }

    /// <summary>
    /// paging extension
    /// </summary>
    /// <param name="entity"></param>
    /// <param name="pageIndex"></param>
    /// <param name="pageSize"></param>
    /// <param name="Field"></param>
    /// <param name="Sort"></param>
    /// <returns></returns>
    public static async Task<BasePageOutput<T>> ToPagedListAsync<T>(List<T> entity, int pageIndex, int pageSize)
        where T : new()
    {
        int total = entity?.Count() ?? 0;
        var totalPages = (int)Math.Ceiling(total / (double)pageSize);
        var items = entity?.Skip((pageIndex - 1) * pageSize)
                ?.Take(pageSize)?.ToList() ?? null;
        return new BasePageOutput<T>
        {
            Page = pageIndex,
            PageSize = pageSize,
            Items = items,
            Total = total,
            TotalPages = totalPages,
            HasNextPage = pageIndex < totalPages,
            HasPrevPage = pageIndex - 1 > 0
        };
    }
}
